<template>
  <div class="shop-owner-detail" v-loading="loading">
    <!-- 基本信息 -->
    <el-card class="info-card" shadow="never">
      <template #header>
        <div class="card-header">
          <span class="card-title">基本信息</span>
          <el-tag :type="getStatusType(ownerInfo.status)" size="small">
            {{ ownerInfo.statusName }}
          </el-tag>
        </div>
      </template>
      
      <el-descriptions :column="2" border class="owner-descriptions">
        <el-descriptions-item label="业主姓名" label-class-name="desc-label">
          <span class="desc-value name-text">{{ ownerInfo.ownerName }}</span>
        </el-descriptions-item>
        <el-descriptions-item label="业主类型" label-class-name="desc-label">
          <el-tag :type="ownerInfo.ownerType === 1 ? 'success' : 'primary'" size="small">
            {{ ownerInfo.ownerTypeName }}
          </el-tag>
        </el-descriptions-item>
        <el-descriptions-item label="联系电话" label-class-name="desc-label">
          <span class="desc-value">{{ ownerInfo.ownerPhone }}</span>
        </el-descriptions-item>
        <el-descriptions-item label="身份证号" label-class-name="desc-label">
          <span class="desc-value">{{ maskIdCard(ownerInfo.ownerIdCard) }}</span>
        </el-descriptions-item>
        <el-descriptions-item label="企业名称" label-class-name="desc-label" v-if="ownerInfo.ownerType === 2">
          <span class="desc-value">{{ ownerInfo.companyName || '-' }}</span>
        </el-descriptions-item>
        <el-descriptions-item label="营业执照号" label-class-name="desc-label" v-if="ownerInfo.ownerType === 2">
          <span class="desc-value">{{ ownerInfo.companyLicense || '-' }}</span>
        </el-descriptions-item>
        <el-descriptions-item label="联系地址" label-class-name="desc-label">
          <span class="desc-value">{{ ownerInfo.contactAddress || '-' }}</span>
        </el-descriptions-item>
        <el-descriptions-item label="邮箱" label-class-name="desc-label">
          <span class="desc-value">{{ ownerInfo.email || '-' }}</span>
        </el-descriptions-item>
        <el-descriptions-item label="创建时间" label-class-name="desc-label">
          <span class="desc-value">{{ formatDateTime(ownerInfo.createTime) }}</span>
        </el-descriptions-item>
        <el-descriptions-item label="更新时间" label-class-name="desc-label">
          <span class="desc-value">{{ formatDateTime(ownerInfo.updateTime) }}</span>
        </el-descriptions-item>
        <el-descriptions-item label="备注" :span="2" label-class-name="desc-label">
          <span class="desc-value">{{ ownerInfo.remark || '无' }}</span>
        </el-descriptions-item>
      </el-descriptions>
    </el-card>

    <!-- 关联店铺列表 -->
    <el-card class="shops-card" shadow="never">
      <template #header>
        <div class="card-header">
          <span class="card-title">关联店铺</span>
          <span v-if="ownerInfo.shopList?.length" class="shop-count">
            共 {{ ownerInfo.shopList.length }} 个店铺
          </span>
        </div>
      </template>
      
      <div class="shops-container">
        <el-table
          v-if="shopList && shopList.length > 0"
          :data="shopList"
          stripe
          border
          style="width: 100%"
          max-height="400"
          :header-cell-style="tableHeaderStyle"
          :cell-style="tableCellStyle"
        >
          <el-table-column prop="shopName" label="店铺名称" min-width="150" show-overflow-tooltip />
          
          <el-table-column prop="relationTypeName" label="关系类型" width="100" align="center">
            <template #default="{ row }">
              <el-tag :type="getRelationTypeTagType(row.relationType)" size="small">
                {{ row.relationTypeName }}
              </el-tag>
            </template>
          </el-table-column>
          
          <el-table-column prop="ownershipRatio" label="所有权比例" width="120" align="center">
            <template #default="{ row }">
              <span v-if="row.ownershipRatio && typeof row.ownershipRatio === 'number'" class="ratio-text">{{ row.ownershipRatio }}%</span>
              <span v-else class="text-placeholder">-</span>
            </template>
          </el-table-column>
          
          <el-table-column prop="rentPrice" label="租金" width="120" align="right">
            <template #default="{ row }">
              <span v-if="row.rentPrice && typeof row.rentPrice === 'number'" class="price-text">¥{{ row.rentPrice.toFixed(2) }}</span>
              <span v-else class="text-placeholder">-</span>
            </template>
          </el-table-column>
          
          <el-table-column label="租赁期间" width="200" show-overflow-tooltip>
            <template #default="{ row }">
              <span v-if="row.leaseStartDate && row.leaseEndDate" class="date-range">
                {{ formatDate(row.leaseStartDate) }} - {{ formatDate(row.leaseEndDate) }}
              </span>
              <span v-else class="text-placeholder">-</span>
            </template>
          </el-table-column>
          
          <el-table-column prop="isPrimary" label="主要联系人" width="100" align="center">
            <template #default="{ row }">
              <el-tag 
                v-if="row.isPrimary === 1" 
                type="success" 
                size="small"
              >
                是
              </el-tag>
              <span v-else class="text-placeholder">否</span>
            </template>
          </el-table-column>
          
          <el-table-column prop="statusName" label="状态" width="80" align="center">
            <template #default="{ row }">
              <el-tag :type="row.status === 1 ? 'success' : 'danger'" size="small">
                {{ row.statusName }}
              </el-tag>
            </template>
          </el-table-column>
        </el-table>
        
        <el-empty v-else description="暂无关联店铺" :image-size="80" />
      </div>
    </el-card>

    <!-- 操作按钮 -->
    <div class="action-buttons">
      <el-button type="primary" @click="handleEdit">
        <el-icon><Edit /></el-icon>
        编辑业主
      </el-button>
      <el-button type="info" @click="handleClose">
        <el-icon><Close /></el-icon>
        关闭
      </el-button>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import { Edit, Close } from '@element-plus/icons-vue'
import { shopOwnerApi } from '@/api/shop-owner'
import { shopOwnerRelationApi } from '@/api/shop-owner-relation'
import type { ShopOwnerVO, ShopOwnerRelationVO } from '../types'

// Props
interface Props {
  ownerId: number
}

const props = defineProps<Props>()

// Emits
const emit = defineEmits<{
  edit: [ownerId: number]
  close: []
}>()

// 响应式数据
const loading = ref(false)
const ownerInfo = ref<ShopOwnerVO>({} as ShopOwnerVO)
const shopList = ref<ShopOwnerRelationVO[]>([])

// 表格样式
const tableHeaderStyle = {
  background: '#f5f7fa',
  color: '#606266',
  fontWeight: '600',
  fontSize: '14px'
}

const tableCellStyle = {
  fontSize: '13px',
  padding: '8px 0'
}

// 生命周期
onMounted(() => {
  loadOwnerDetail()
})

// 方法
const loadOwnerDetail = async () => {
  loading.value = true
  try {
    // 并行加载业主详情和关联店铺列表
    const [ownerResponse, shopResponse] = await Promise.all([
      shopOwnerApi.getShopOwnerDetail(props.ownerId),
      shopOwnerRelationApi.getShopsByOwnerId(props.ownerId)
    ])
    
    // 处理业主详情
    if (ownerResponse && ownerResponse.code === 200 && ownerResponse.data) {
      ownerInfo.value = ownerResponse.data
      console.log('业主详情数据加载成功:', ownerInfo.value)
    } else {
      ElMessage.error(ownerResponse?.message || '业主信息不存在')
    }
    
    // 处理关联店铺列表
    if (shopResponse && shopResponse.code === 200 && shopResponse.data) {
      shopList.value = shopResponse.data
      console.log('关联店铺列表数据加载成功:', shopList.value)
    } else {
      console.warn('关联店铺列表API响应错误:', shopResponse)
      shopList.value = []
    }
  } catch (error) {
    ElMessage.error('加载业主详情失败')
    console.error('加载业主详情失败:', error)
  } finally {
    loading.value = false
  }
}

const handleEdit = () => {
  emit('edit', props.ownerId)
}

const handleClose = () => {
  emit('close')
}

// 工具方法
const getStatusType = (status?: number) => {
  switch (status) {
    case 1: return 'success'
    case 0: return 'danger'
    default: return 'info'
  }
}

const getRelationTypeTagType = (relationType?: number) => {
  switch (relationType) {
    case 1: return 'success' // 业主
    case 2: return 'warning' // 租户
    case 3: return 'info'     // 联合业主
    default: return 'info'
  }
}

const maskIdCard = (idCard?: string) => {
  if (!idCard) return '-'
  if (idCard.length < 8) return idCard
  return idCard.substring(0, 4) + '****' + idCard.substring(idCard.length - 4)
}

const formatDateTime = (dateTime?: string) => {
  if (!dateTime) return '-'
  return new Date(dateTime).toLocaleString('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit'
  })
}

const formatDate = (date?: string) => {
  if (!date) return '-'
  return new Date(date).toLocaleDateString('zh-CN')
}
</script>

<style scoped>
.shop-owner-detail {
  padding: 0;
}

.info-card,
.shops-card {
  margin-bottom: 20px;
}

.shops-card:last-child {
  margin-bottom: 0;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 0;
}

.card-title {
  font-size: 16px;
  font-weight: 600;
  color: #303133;
}

.shop-count {
  font-size: 12px;
  color: #909399;
  background: #f5f7fa;
  padding: 2px 8px;
  border-radius: 4px;
}

.owner-descriptions {
  margin: 0;
}

:deep(.desc-label) {
  background: #fafbfc !important;
  color: #606266 !important;
  font-weight: 500 !important;
  width: 120px !important;
  text-align: right !important;
  padding-right: 16px !important;
}

.desc-value {
  color: #303133;
  font-weight: 400;
}

.name-text {
  font-weight: 600;
  color: #303133;
  font-size: 16px;
}

.shops-container {
  padding: 0;
}

.ratio-text {
  color: #409eff;
  font-weight: 500;
}

.price-text {
  color: #67c23a;
  font-weight: 600;
}

.date-range {
  font-size: 12px;
  color: #606266;
  line-height: 1.4;
}

.text-placeholder {
  color: #c0c4cc;
  font-style: italic;
}

.action-buttons {
  margin-top: 30px;
  text-align: center;
  padding-top: 20px;
  border-top: 1px solid #e4e7ed;
}

.action-buttons .el-button {
  margin: 0 8px;
}

:deep(.el-card__header) {
  background-color: #f5f7fa;
  border-bottom: 1px solid #e4e7ed;
  padding: 12px 20px;
}

:deep(.el-card__body) {
  padding: 20px;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .shop-owner-detail {
    padding: 0;
  }
  
  .info-card,
  .shops-card {
    margin-bottom: 16px;
  }
  
  .card-header {
    flex-direction: column;
    align-items: flex-start;
    gap: 8px;
  }
  
  .shops-container {
    overflow-x: auto;
  }
}
</style>
